<?php
/**
 * @file stationmessage.php $
 * @author LinLin (linlin@haibao.com) $
 * @date 2015年8月18日 下午14:27:50 $
 * @brief app 站内消息 $
 */
namespace haibao\app\business;

use haibao\app\data\StationMessage as StationMessageData;

class StationMessage extends \haibao\app\business\Base {
	
	/**
	 * 获取站内消息列表
	 */
	public static function getStationMessage($query){
		$stationMessageData = new StationMessageData();
		return $stationMessageData->getAll($query);
	}
	
	/**
	 * 根据Id获取单条站内消息
	 */
	public static function getStationMessageById($id){
		$stationMessageData = new StationMessageData();
		return $stationMessageData->getOneById($id);
	}
	
	/**
	 * 添加站内信息
	 */
	public static function saveStationMessage($model){
		self::checkOperation(self::FUNC_CODE_APP_STATION_MESSAGE_ADD);
		$model->CreateTime = new \DateTime();
		self::checkForm($model);
		$model->CreateBy = self::getCurrentUser()->Id;
		$model->Author = self::getCurrentUser()->RealName;
		$stationMessageData = new StationMessageData();
		$stationMessageData->saveStationMessage($model);
		self::saveOperateHistory(self::FUNC_CODE_APP_STATION_MESSAGE_ADD, $model->toArray(true,true));
	}
	
	/**
	 * 表单验证
	 * @param \haibao\app\model\data\Article $model
	 */
	private static function checkForm($model){
		if(!isset($model->PushObject)){
			throw new BusinessException('发送对象不能为空');
		}
		if(!$model->Title){
			throw new BusinessException('标题不能为空');
		}
		
		if(!isset($model->LinkType) && isset($model->Link) || isset($model->LinkType) && !isset($model->Link)){
			throw new BusinessException('若填写跳转类型，则跳转对象必填');
		}
		
		if(!isset($model->LinkType) && !isset($model->Content)){
			throw new BusinessException('跳转对象或内容二选一');
		}
		
		if(isset($model->LinkType) && $model->LinkType == \haibao\app\model\data\StationMessage::LINK_TYPE_HTML){
			if(substr(trim($model->Link),0,4) != 'http'){
				$model->Link = 'http://'.trim($model->Link);
			}
		}
		
		if($model->PubStatus == 0 && $model->PublishTime == ''){
			throw new BusinessException('若预发布，请填写时间');
		}
		if($model->PubStatus == 0 && $model->PublishTime < $model->CreateTime->format('Y-m-d H:i:s')){
			throw new BusinessException('预发布时间需大于当前时间');
		}
		
		if($model->UserId){
			$checkStr = '/^[，,0-9]*$/';
			if(!preg_match($checkStr, $model->UserId, $match)){
				throw new BusinessException('用户ID有特殊字符，请重新填写');
			}
		}
	}
	
	/**
	 * 删除站内消息
	 */
	public static function changeMessageStatus($id, $status){
		self::checkOperation(self::FUNC_CODE_APP_STATION_MESSAGE_DELETE);
		$stationMessageData = new StationMessageData();
		$stationMessageData->updateMessageStatus($id, $status);
		self::saveOperateHistory(self::FUNC_CODE_APP_STATION_MESSAGE_DELETE, $status);
	}
}
